
const Blog = require('../model/blog.model')
const { Op } = require("sequelize")
class blogService {
  async getBlog(params){
    const { count, rows } = await Blog.findAndCountAll(
      {
        limit:params.pageSize,
        offset:(params.pageNo -1) * params.pageSize,
        where:{[Op.or]:[{firstClass:params.firstClass?params.firstClass:''},{secondClass:params.secondClass?params.secondClass:''}]} 
      },
    )
    return {
      rows,
      count
    }
  }
  async getOneBlog(params) {
    const res = await Blog.findOne({
      where:{id:params.id}
    })
    return res
  }
  async viewBlog(params){
    const res = await Blog.update(
      { view:Number(params.view) + 1 },
      { where:{ id:params.id } }
    )
    return res
  }
  async likeBlog(params){
    const res = await Blog.update(
      { like:Number(params.like) + 1 },
      { where:{ id:params.id } }
    )
    return res
  }
  async addBlog(params){
    const json = await Note.create(params)
    if(json){
      return true
    }
  }
  async searchSelect(params){
    const res = await Blog.findAll({
      where:{
        isSelected:"0"
      }
    })
    return res
  }
  //分页查询
  async search(params){
    let obj = Object.assign({},params)
    delete obj.pageNo
    delete obj.pageSize
    const { count, rows } = await Blog.findAndCountAll({
        limit:params.pageSize,
        offset:(params.pageNo -1) * params.pageSize,
        where:{
          ...obj,
          // [Op.or]:[
          //   {
          //     title:{
          //       [Op.like]: params.title?params.title:''
          //     }
          //   },
          //   {
          //     author:{
          //       [Op.like]: params.author
          //     }
          //   },
          //   {
          //     createTime:{
          //       [Op.like]: params.createTime
          //     }
          //   }
          // ]
        }
    })
    return {
      rows,
      count
    }
  }
  //模糊查询
  async searchLike(params){
    let obj = Object.assign({},params)
    delete obj.pageNo
    delete obj.pageSize
    const { count, rows } = await Blog.findAndCountAll({
        limit:params.pageSize,
        offset:(params.pageNo -1) * params.pageSize,
        where:{
          title:{
            [Op.like]:'%'+params.title+'%'     
          } 
        }
    })
    return {
      rows,
      count
    }
  }
  //新增
  async insertItem(params){
    const res = await Blog.create(params)
    return res
  }
  //修改
  async updateItem(params){
    const res = await Blog.update(
      {...params},
      { where:{id:params.id} }
    )
    return res
  }
  //删除
  async deleteOne(params){
    const res = await Blog.destroy({ where:{ id:params.id } })
    return res
  }
  //查询一条信息
  async getOne(params){
    const res = await Blog.findOne({
      where:{ id:params.id }
    })
    return res
  }
}

module.exports = new blogService()